<template>
    <div class="task-detail-container" style="margin-bottom: 50px; padding-bottom: 10px;">
        <van-nav-bar title="任务详情" left-text="" left-arrow fixed @click-left="onClickLeft">
            <template #left>
                <van-icon name="arrow-left" size="24" color="gray" />
            </template>
        </van-nav-bar>

        <div class="content">
            <!-- 任务基本信息 -->
            <div class="task-card">
                <div class="p-4">
                    <h2 class="text-xl font-bold text-gray-800 mb-2">{{ taskDetail.taskTitle }}</h2>
                    <div class="task-meta-info">
                        <div class="publish-time">
                            <van-icon name="clock-o" class="meta-icon" />
                            <span>发布于 {{ formatDate(taskDetail.createTime) }}</span>
                        </div>
                        <div class="stats-container">
                            <div class="stat-item">
                                <van-icon name="eye-o" class="meta-icon" />
                                <span>{{ taskDetail.viewCount }}人浏览</span>
                            </div>
                            <div class="stat-item">
                                <van-icon name="star-o" class="meta-icon" />
                                <span>{{ taskDetail.collectCount }}人收藏</span>
                            </div>
                        </div>
                    </div>

                    <div class="flex flex-wrap mb-6 tag-container">
                        <div class="custom-tag location-tag">
                            <van-icon name="location-o" class="tag-icon" />
                            <span class="ellipsis">{{ taskDetail.taskAddress }}</span>
                        </div>
                        <div class="custom-tag job-tag">
                            <van-icon name="clock-o" class="tag-icon" /> {{ getJobTypeText(taskDetail.jobType) }}
                        </div>
                        <div class="custom-tag category-tag">
                            <van-icon name="manager-o" class="tag-icon" /> {{ getCategoryName(taskDetail.taskCategoryId)
                            }}
                        </div>
                        <div class="custom-tag experience-tag">
                            <van-icon name="certificate" class="tag-icon" /> {{
                                getExperienceText(taskDetail.experienceRequirement) }}
                        </div>
                    </div>

                    <div class="info-grid">
                        <van-cell-group inset class="custom-cell-group">
                            <van-cell center class="info-cell">
                                <template #title>
                                    <div class="cell-title">薪资待遇</div>
                                </template>
                                <template #value>
                                    <div class="cell-value salary-value">
                                        ¥{{ taskDetail.salary }}{{ getSalaryTypeText(taskDetail.salaryType) }}
                                    </div>
                                </template>
                                <template #icon>
                                    <van-icon name="cash-back-record" class="cell-icon salary-icon" />
                                </template>
                            </van-cell>

                            <van-cell center class="info-cell">
                                <template #title>
                                    <div class="cell-title">工作时间</div>
                                </template>
                                <template #value>
                                    <div class="cell-value time-value">
                                        {{ taskDetail.workTime || '8:00-17:00' }}
                                    </div>
                                </template>
                                <template #icon>
                                    <van-icon name="clock-o" class="cell-icon time-icon" />
                                </template>
                            </van-cell>

                            <van-cell center class="info-cell">
                                <template #title>
                                    <div class="cell-title">结算方式</div>
                                </template>
                                <template #value>
                                    <div class="cell-value settlement-value">
                                        {{ getSettlementText(taskDetail.settlementType) }}
                                    </div>
                                </template>
                                <template #icon>
                                    <van-icon name="balance-pay" class="cell-icon settlement-icon" />
                                </template>
                            </van-cell>
                        </van-cell-group>
                    </div>
                </div>

                <div class="bg-gray-50 p-4 border-t border-gray-200">
                    <div class="flex items-center mb-4">
                        <van-image round width="48" height="48"
                            :src="taskDetail.publisherAvatar || 'https://randomuser.me/api/portraits/women/68.jpg'"
                            class="mr-4"
                            @error="() => { taskDetail.publisherAvatar = '' }" />
                        <div>
                            <h4 class="font-medium text-gray-800">{{ taskDetail.publisherName }}</h4>
                            <div class="flex items-center">
                                <div class="flex text-yellow-400 mr-2">
                                    <van-rate v-model="taskDetail.publisherRating" readonly allow-half :count="5"
                                        size="12" />
                                </div>
                                <span class="text-sm text-gray-500">{{ taskDetail.publisherRating }} ({{
                                    taskDetail.ratingCount
                                }}条评价)</span>
                            </div>
                        </div>
                    </div>
                    <div class="button-group">
                        <van-button v-if="taskDetail.taskStatus == 0 && isApplied()" type="primary" block
                            color="#4f46e5" @click="applyTask" class="action-button">
                            <van-icon name="friends-o" class="mr-2" /> 立即申请
                        </van-button>
                        <van-button plain block color="#4f46e5" @click="contactPublisher" class="action-button">
                            <van-icon name="phone-o" class="mr-2" /> 联系发布者
                        </van-button>
                    </div>
                </div>
            </div>

            <!-- 工作地点 -->
            <div class="task-card location-section">
                <h3 class="section-title">
                    <van-icon name="location" class="section-icon" />
                    工作地点
                </h3>
                <div class="location-map">
                    <div class="location-info">
                        <van-icon name="location" class="location-icon" />
                        <p class="location-text">{{ taskDetail.taskAddress || '' }}</p>
                    </div>
                </div>
                <div class="transport-info">
                    <div class="transport-item">
                        <van-icon name="guide-o" class="transport-icon subway-icon" />
                        <span class="transport-text">{{ taskDetail.transportInfo?.subway || ''
                            }}</span>
                    </div>
                    <div class="transport-item">
                        <van-icon name="logistics" class="transport-icon bus-icon" />
                        <span class="transport-text">{{ taskDetail.transportInfo?.bus || '' }}</span>
                    </div>
                </div>
            </div>

            <!-- 相似任务推荐 -->
            <div class="task-card similar-tasks-section">
                <div class="section-header">
                    <h3 class="section-title">
                        <van-icon name="friends-o" class="section-icon" />
                        相似任务推荐
                    </h3>
                </div>
                <div class="similar-tasks-grid">
                    <div v-for="(task, index) in similarTasks.filter(task => task.taskStatus === 0)" :key="index" class="similar-task-card"
                        @click="viewTaskDetail(task.taskId)">
                        <div class="task-content">
                            <h4 class="task-title">{{ task.taskTitle }}</h4>
                            <div class="task-location">
                                <van-icon name="location" class="location-icon" />
                                <span class="location-text">{{ task.taskAddress }}</span>
                            </div>
                            <div class="task-salary">
                                <span class="salary-amount">¥{{ task.salary }}</span>
                                <span class="salary-unit">{{ getSalaryTypeText(task.salaryType) }}</span>
                            </div>
                            <div class="task-tags">
                                <span class="task-tag job-type">
                                    <van-icon name="clock" />
                                    {{ getJobTypeText(task.jobType) }}
                                </span>
                                <span class="task-tag category-type">
                                    <van-icon name="manager-o" />
                                    {{ getCategoryName(task.taskCategoryId) }}
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast, showDialog } from 'vant'
import network from '../network'

const router = useRouter()
const route = useRoute()
const taskId = ref(Number(route.params.id) || 0)

// 任务详情数据
const taskDetail = reactive({
    taskId: 0,
    taskTitle: '',
    taskDescription: '',
    taskAddress: '',
    salary: 0,
    salaryType: 2, // 默认按天
    jobType: 1, // 默认临时工
    taskCategoryId: 1, // 默认护理服务
    taskStatus: 1, // 默认待发布
    experienceRequirement: 0, // 默认无需经验
    settlementType: 1, // 默认日结
    workTime: '8:00-17:00',
    createTime: '',
    viewCount: 0,
    collectCount: 0,
    publisherId: 0,
    publisherName: '',
    publisherAvatar: '',
    publisherRating: 4.8,
    ratingCount: 0,
    jobDescription: '',
    jobRequirements: '',
    benefits: '',
    transportInfo: {
        subway: '',
        bus: ''
    }
})

// 相似任务推荐
const similarTasks = ref<any[]>([])

// 获取任务详情
const getTaskDetail = async () => {
    try {
        if (!taskId.value) return
        network.getTaskDetail(taskId.value)
            .then((res: any) => {
                if (res.data.code == 100) {
                    Object.assign(taskDetail, res.data.data)
                    network.getAvatarById(taskDetail.publisherId)
                      .then((res: any) => {
                            if (res.data.code == 100 && res.data.data && res.data.data.avatarData) {
                                taskDetail.publisherAvatar = res.data.data.avatarData
                            } else {
                                // 设置为空字符串，触发默认头像显示
                                taskDetail.publisherAvatar = ''
                                console.warn(`获取用户 ${taskDetail.publisherId} 头像失败: ${res.data?.message}`)
                            }
                        })
                        .catch(error => {
                            taskDetail.publisherAvatar = ''
                            console.error(`获取用户 ${taskDetail.publisherId} 头像异常:`, error)
                        })
                }
            })

    } catch (error) {
        console.error('获取任务详情失败:', error)
        showToast('获取任务详情失败，请稍后重试')
    }
}

// 获取相似任务
const getSimilarTasks = async () => {
    network.getSimilarTasks(taskId.value)
        .then((res: any) => {
            if (res.data.code == 100) {
                similarTasks.value = res.data.data
            }
        })
}

// 格式化日期
const formatDate = (dateString: string) => {
    if (!dateString) return ''

    const date = new Date(dateString)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')

    return `${year}-${month}-${day}`
}

// 获取薪资类型文本
const getSalaryTypeText = (salaryType: number) => {
    const types = {
        1: '/小时',
        2: '/天',
        3: '/周',
        4: '/月',
        5: '/次'
    }
    return types[salaryType as keyof typeof types] || '/天'
}

// 获取工作类型文本
const getJobTypeText = (jobType: number) => {
    const types = {
        1: '临时工',
        2: '兼职',
        3: '全职',
        4: '实习'
    }
    return types[jobType as keyof typeof types] || '临时工'
}

// 获取分类名称
const getCategoryName = (categoryId: number) => {
    const categories = {
        1: '电工',
        2: '水工',
        3: '护理服务',
        4: '搬运',
        5: '保洁',
        6: '护理',
    }
    return categories[categoryId as keyof typeof categories] || '其他'
}

// 获取经验要求文本
const getExperienceText = (experience: number) => {
    const experiences = {
        0: '无需经验',
        1: '1年以下',
        2: '1-3年',
        3: '3-5年',
        4: '5年以上'
    }
    return experiences[experience as keyof typeof experiences] || '无需经验'
}

// 获取结算方式文本
const getSettlementText = (settlementType: number) => {
    const types = {
        1: '日结',
        2: '周结',
        3: '月结',
        4: '完工结'
    }
    return types[settlementType as keyof typeof types] || '日结'
}

// 返回上一页
const onClickLeft = () => {
    router.back()
}

// 申请任务
const applyTask = () => {
    showDialog({
        title: '申请确认',
        message: '确定要申请该任务吗？',
        showCancelButton: true,
    }).then(() => {
        if (!taskId.value) return

        network.applyTask(taskId.value)
            .then((res: any) => {
                if (res.code === 100) {
                    showToast('申请成功')
                } else {
                    showToast(res.message || '申请失败')
                }
            })
            .catch(err => {
                showToast('申请失败，请稍后重试')
                console.error('申请任务失败:', err)
            })
    }).catch(() => {
        // 取消申请 
        showToast('取消申请')
    })
}

// 联系发布者
const contactPublisher = () => {
    network.getPublisherInfo(taskDetail.publisherId)
       .then((res: any) => {
            const contactPhone = res.data.phone
            showDialog({
                title: '联系发布者',
                message: `联系电话：${contactPhone}`,
                showCancelButton: true,
            })
       })
}

// 查看任务详情
const viewTaskDetail = (id: number) => {
    router.push(`/task-detail/${id}`)
}

const isApplied = () => {
    network.isAlreadyApplied(taskId.value)
        .then((res: any) => {
            if (res.code === 100 && res.data.length >= 0) {
                return res.data
            } else {
                showToast(res.message || '申请失败')
            }
        })
}

// 组件挂载时加载数据
onMounted(() => {
    getTaskDetail()
    getSimilarTasks()
})
</script>

<style scoped>
.task-detail-container {
    min-height: 80vh;
    background-color: #f7f8fa;
    padding-bottom: 50px;
}

.content {
    padding-top: 46px;
}

.task-card {
    background-color: #fff;
    border-radius: 20px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    margin: 20px;
    margin-bottom: 20px;
    overflow: hidden;
    padding: 20px;
}

:deep(.van-nav-bar) {
    background-color: #fff;
}

:deep(.van-nav-bar__title) {
    font-size: 18px;
    font-weight: bold;
    color: #333;
}

:deep(.van-button--primary) {
    background-color: #4f46e5;
    border-color: #4f46e5;
}

:deep(.van-button--plain) {
    color: #4f46e5;
    border-color: #4f46e5;
}

:deep(.van-tag--plain) {
    background-color: transparent;
}

:deep(.van-tag--primary) {
    color: #0369a1;
    border-color: #0369a1;
}

:deep(.van-tag--success) {
    color: #15803d;
    border-color: #15803d;
}

:deep(.van-tag--warning) {
    color: #7e22ce;
    border-color: #7e22ce;
}

:deep(.van-tag--danger) {
    color: #854d0e;
    border-color: #854d0e;
}

.info-grid {
    margin: 20px 0;
    background: linear-gradient(145deg, #ffffff, #f3f4f6);
    border-radius: 16px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
    overflow: hidden;
}

.custom-cell-group {
    background: transparent !important;
}

.info-cell {
    position: relative;
    margin: 12px;
    background: rgba(255, 255, 255, 0.8);
    border-radius: 12px;
    transition: all 0.3s ease;
}

.info-cell:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.cell-title {
    font-size: 14px;
    color: #64748b;
    font-weight: 500;
}

.cell-value {
    font-size: 16px;
    font-weight: 600;
    letter-spacing: 0.5px;
}

.cell-icon {
    font-size: 24px;
    padding: 8px;
    border-radius: 50%;
    margin-right: 12px;
}

.salary-value {
    color: #6366f1;
    background: linear-gradient(45deg, #6366f1, #818cf8);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
}

.salary-icon {
    color: #6366f1;
    background: rgba(99, 102, 241, 0.1);
}

.time-value {
    color: #10b981;
    background: linear-gradient(45deg, #10b981, #34d399);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
}

.time-icon {
    color: #10b981;
    background: rgba(16, 185, 129, 0.1);
}

.settlement-value {
    color: #f59e0b;
    background: linear-gradient(45deg, #f59e0b, #fbbf24);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
}

.settlement-icon {
    color: #f59e0b;
    background: rgba(245, 158, 11, 0.1);
}

:deep(.van-cell) {
    padding: 16px;
    background: transparent;
}

:deep(.van-cell::after) {
    display: none;
}

:deep(.van-cell-group--inset) {
    margin: 0;
}

.button-group {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;
    margin: 24px 0;
    text-align: center;
    display: flex;
}

.action-button {
    width: 100%;
    height: 44px;
    font-size: 16px;
    border-radius: 20px;
}

.ellipsis {
    max-width: 6em;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    display: inline-block;
    vertical-align: middle;
}

.tag-container {
    gap: 12px;
    padding: 4px 0;
}

.custom-tag {
    display: inline-flex;
    align-items: center;
    padding: 8px 16px;
    border-radius: 20px;
    font-size: 14px;
    font-weight: 500;
    background-color: #f3f4f6;
    color: #6366f1;
    transition: all 0.3s ease;
    margin: 5px;
}

.tag-icon {
    font-size: 16px;
    margin-right: 6px;
    color: #6366f1;
}

.location-tag,
.job-tag,
.category-tag,
.experience-tag {
    background-color: #f3f4f6;
    color: #6366f1;
}

.custom-tag:hover {
    background-color: #e5e7eb;
    transform: translateY(-2px);
}

:deep(.location-tag) {
    color: #0284c7;
    border-color: #0284c7;
    background-color: rgba(2, 132, 199, 0.05);
}

:deep(.job-tag) {
    color: #059669;
    border-color: #059669;
    background-color: rgba(5, 150, 105, 0.05);
}

:deep(.category-tag) {
    color: #7c3aed;
    border-color: #7c3aed;
    background-color: rgba(124, 58, 237, 0.05);
}

:deep(.experience-tag) {
    color: #d97706;
    border-color: #d97706;
    background-color: rgba(217, 119, 6, 0.05);
}

.task-meta-info {
    background: linear-gradient(to right, rgba(249, 250, 251, 0.8), rgba(243, 244, 246, 0.8));
    border-radius: 12px;
    padding: 12px 16px;
    margin-bottom: 16px;
}

.publish-time {
    display: flex;
    align-items: center;
    color: #64748b;
    font-size: 14px;
    margin-bottom: 8px;
    padding-bottom: 8px;
    border-bottom: 1px dashed rgba(100, 116, 139, 0.2);
}

.stats-container {
    display: flex;
    gap: 16px;
}

.stat-item {
    display: flex;
    align-items: center;
    color: #64748b;
    font-size: 14px;
}

.meta-icon {
    font-size: 16px;
    margin-right: 6px;
    color: #6366f1;
}

.info-card {
    display: flex;
    align-items: center;
    padding: 20px;
    margin-bottom: 16px;
    border-radius: 16px;
    background: linear-gradient(145deg, #ffffff, #f8fafc);
    border-radius: 20px;
    overflow: hidden;
}

.section-header {
    padding: 20px;
    border-bottom: 1px solid rgba(0, 0, 0, 0.05);
    margin-bottom: 20px;
}

.section-title {
    display: flex;
    align-items: center;
    font-size: 18px;
    font-weight: 600;
    color: #1e293b;
    margin: 0;
}

.section-icon {
    font-size: 24px;
    margin-right: 12px;
    color: #6366f1;
    background: linear-gradient(135deg, #6366f1, #818cf8);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
}

.similar-tasks-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;
    padding: 0 20px 20px;
}

.similar-task-card {
    position: relative;
    background: white;
    border-radius: 16px;
    overflow: hidden;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    border: 1px solid rgba(99, 102, 241, 0.1);
    cursor: pointer;
    position: relative;
    isolation: isolate;
}

.similar-task-card::before {
    content: '';
    position: absolute;
    inset: 0;
    background: linear-gradient(135deg, rgba(99, 102, 241, 0.1), rgba(129, 140, 248, 0.1));
    opacity: 0;
    transition: opacity 0.3s ease;
    z-index: -1;
}

.similar-task-card:hover {
    transform: translateY(-4px);
    box-shadow: 0 12px 24px rgba(0, 0, 0, 0.1);
    border-color: rgba(99, 102, 241, 0.2);
}

.similar-task-card:hover::before {
    opacity: 1;
}

.similar-task-card:active {
    transform: translateY(-2px);
    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.08);
}

.task-content {
    padding: 16px;
    position: relative;
    z-index: 1;
}

/* 添加点击波纹效果 */
.similar-task-card::after {
    content: '';
    position: absolute;
    width: 100px;
    height: 100px;
    background: radial-gradient(circle, rgba(99, 102, 241, 0.2) 0%, transparent 60%);
    border-radius: 50%;
    opacity: 0;
    transform: translate(-50%, -50%) scale(0);
    transition: transform 0.4s ease-out, opacity 0.3s ease-out;
    pointer-events: none;
}

.similar-task-card:active::after {
    opacity: 1;
    transform: translate(-50%, -50%) scale(4);
}

.task-title {
    font-size: 16px;
    font-weight: 600;
    color: #1e293b;
    margin-bottom: 12px;
    line-height: 1.4;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

.task-location {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
    color: #64748b;
    font-size: 13px;
}

.location-icon {
    font-size: 16px;
    margin-right: 6px;
    color: #6366f1;
}

.location-text {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.task-salary {
    margin-bottom: 12px;
}

.salary-amount {
    font-size: 18px;
    font-weight: 700;
    background: linear-gradient(45deg, #6366f1, #818cf8);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    margin-right: 4px;
}

.salary-unit {
    font-size: 13px;
    color: #64748b;
}

.task-tags {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
}

.task-tag {
    display: inline-flex;
    align-items: center;
    padding: 4px 8px;
    border-radius: 6px;
    font-size: 12px;
    font-weight: 500;
}

.task-tag .van-icon {
    font-size: 14px;
    margin-right: 4px;
}

.job-type {
    color: #059669;
    background: rgba(5, 150, 105, 0.1);
}

.category-type {
    color: #7c3aed;
    background: rgba(124, 58, 237, 0.1);
}
</style>